using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Admin;
using PHSRAG.Insight21.Agreements;
using PHSRAG.Insight21.CDS;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.ClinicalTrials
{
    /// <summary>
    /// Provides functionality for initial setup of a new budget
    /// </summary>
    public partial class BudgetSetup : NoCachePage
    {
        #region Constants

        /// <summary>
        /// The configuration key that holds the name of the staging folder
        /// </summary>
        private const string StagingFolder_ConfigKey = "StagingFolder";
        private DataTable userDTAccess;

        #endregion

        private readonly CheckBox mpending = new CheckBox();
        private readonly CheckBox rfinal = new CheckBox();
        private readonly CheckBox rpending = new CheckBox();
        private Budget budget;
        private ICachePolicy cachePolicy;

        /// <summary>
        /// Holds the error messages that should be displayed to the user upon processing the current request.
        /// </summary>
        private string errorReport = string.Empty;

        protected Button FindUser;
        protected Label Label1;
        protected TextBox PIAccessId;
        protected Label PIAccessName;
        protected TextBox Textbox1;
        private UserContext userContext;

        public DataTable UserDTAccess
        {
            get
            {
                if (userDTAccess == null)
                {
                    userContext = (UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey);

                    userDTAccess = DataAccess.GetDataTable(
                        DataAccess.GetConnectionString(),
                        "GetUserToAccessClinicalTrials",
                        DataAccess.BuildSqlParameterArray("@domainUserId", SqlDbType.Int, userContext.DomainUserId,
                            "@budgetId", SqlDbType.Int, budget.Id));
                }
                return userDTAccess;
            }
        }

        #region Event Handlers

        private void OnPageLoad(object sender, EventArgs e)
        {
            try
            {
                ClientScript.RegisterStartupScript(GetType(), "load", "onLoad();", true);

                if (studyType.SelectedValue != "ClinicalTrialBudgetStudyTypeOther")
                {
                    otherType.CssClass = "DataInputDisabled";
                    otherType.Enabled = false;
                    otherTypeLabel.Attributes["class"] = "LabelDisabled";
                    otherTypeValidator.Enabled = false;
                }
                else
                {
                    otherType.CssClass = "DataInput";
                    otherType.Enabled = true;
                    otherTypeLabel.Attributes["class"] = "Label";
                    otherTypeValidator.Enabled = true;
                }

                LoadBudget();

                if (!Page.IsPostBack)
                {
                    InitializeControls();
                    LoadControls();
                    BindControls();
                    LoadAccessList();
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        private void LoadAccessList()
        {
            ctAccess.DataSource = UserDTAccess;
            ctAccess.DataBind();
        }

        protected void OnSaveBudget(object sender, EventArgs e)
        {
            try
            {
                SetBudget();
                if (budget.Id == 0)
                {
                    cachePolicy.Cache("RefreshClinicalTrialBudgetResults", true);
                }

                budget.Save(DataAccess.GetConnectionString(), null);
                budgetBuilderOverview.InitializeControls();

                // Sponsor name text
                Sponsor sponsor = new Sponsor(cachePolicy);
                sponsor.Load(DataAccess.GetConnectionString(), budget.SponsorId);
                sponsorName.Text = sponsor.Name;

                User pi = new User(cachePolicy);
                pi.Load(DataAccess.GetConnectionString(), budget.PIPersonId);
                PIName.Text = string.Format("{0} {1}", pi.FirstName, pi.LastName);
                PIId.Text = pi.DomainUserId.ToString();

                cachePolicy.Cache("RefreshClinicalTrialBudgetResults", true);

                AddBlankRow();
            }
            catch (Exception ex)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        private void DisableAllOtherControls()
        {
            otherType.CssClass = "LabelInputDisabled";
            otherType.Enabled = false;
            otherTypeLabel.Attributes["class"] = "LabelInputDisabled";
            otherTypeValidator.Enabled = false;
            otherType.Enabled = false;
            otherType.CssClass = "DataInputDisabled";
            otherTypeLabel.Attributes["class"] = "LabelDisabled";
            otherTypeValidator.Enabled = false;
            negotiatedRateLabel.Attributes["class"] = "LabelDisabled";
            negotiatedRateRequiredValidator.Enabled = false;
            negotiatedRateValueValidator.Enabled = false;
            otherNegotiatedRate.Enabled = false;
            otherNegotiatedRate.CssClass = "DataInputDisabled";
            otherType.Text = null;
        }

        protected void OnCancel(object sender, EventArgs e)
        {
            Response.Redirect(Settings.GetKeyValue("SubNavigation.ClinicalTrials.BudgetBuilderURL", ""));
        }

        protected void OnAddAttachment(object sender, EventArgs e)
        {
            try
            {
                if (newFile.PostedFile.ContentLength > 0)
                {
                    LoadBudget();
                    BudgetAttachment newAttachment = new BudgetAttachment(cachePolicy);
                    newAttachment.ClinicalTrialBudgetId = budget.Id;
                    userContext = (UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey);
                    newAttachment.PersonId = userContext.PersonId;
                    ProcessUploadedFile(newFile.PostedFile, newAttachment);
                    if (errorReport != string.Empty)
                    {
                        annunciator.Message = errorReport;
                    }
                    newAttachment.Save(DataAccess.GetConnectionString());
                    ArrayList attachments = BudgetAttachment.GetDocuments(budget.Id, cachePolicy);
                    attachmentsGrid.DataSource = attachments;
                    attachmentsGrid.DataBind();
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        protected void OnDeleteAttachments(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridItem item in attachmentsGrid.Items)
                {
                    if (((CheckBox) item.Controls[6].Controls[1]).Checked)
                    {
                        BudgetAttachment.DeleteAttachment(Int32.Parse(item.Cells[1].Text));
                    }
                }
                ArrayList attachments = BudgetAttachment.GetDocuments(budget.Id, cachePolicy);
                attachmentsGrid.DataSource = attachments;
                attachmentsGrid.DataBind();
            }
            catch (Exception ex)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        private void OnItemCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                Document doc = new Document(cachePolicy);
                doc.Load(DataAccess.GetConnectionString(), Int32.Parse(e.Item.Cells[1].Text));
                DownloadFile(doc.Name, true, doc.Blob);
            }
            catch (Exception ex)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Writes the contents of the file to the response stream
        /// </summary>
        /// <param name="fname">Name of the file</param>
        /// <param name="forceDownload">Whether or not show the File Download dialogue</param>
        /// <param name="content">the contents of the file</param>
        private void DownloadFile(string fname, bool forceDownload, byte[] content)
        {
            string ext = Path.GetExtension(fname);
            string type = "";
            // set known types based on file extension  
            if (ext != null)
            {
                switch (ext.ToLower())
                {
                    case ".htm":
                    case ".html":
                        type = "text/HTML";
                        break;

                    case ".txt":
                        type = "text/plain";
                        break;

                    case ".doc":
                    case ".rtf":
                        type = "Application/msword";
                        break;

                    case ".pdf":
                        type = "Application/pdf";
                        break;

                    default:
                        type = "application/octet-stream";
                        break;
                }
            }
            if (forceDownload)
            {
                Response.AppendHeader("content-disposition",
                    "attachment; filename=" + fname);
            }
            if (type != "")
            {
                Response.ContentType = type;
            }
            Response.BinaryWrite(content);
            Response.End();
        }

        /// <summary>
        /// Creates a Document object with the file posted to the server and attaches it to the protocolDocument
        /// </summary>
        /// <param name="postedFile">Control that holds the uploaded file details</param>
        /// <param name="budgetAttachment">The ProtocolDocument to which the Document object should be linked</param>
        private void ProcessUploadedFile(HttpPostedFile postedFile, BudgetAttachment budgetAttachment)
        {
            if (postedFile != null)
            {
                try
                {
                    string fileName = Path.GetFileName(postedFile.FileName);
                    if (postedFile.ContentLength > 0)
                    {
                        //store uploaded files in a temporary location, virus scan & upload it to database & set the documentId column of the datatable
                        //string filePath = Utility.Settings.GetKeyValue(StagingFolder_ConfigKey, string.Empty); 
                        string filePath = Path.GetTempPath();
                        if (filePath == string.Empty)
                        {
                            throw new Exception("Missing configuration entry that specifies the folder to store the attachments");
                        }

                        int domainUserID = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).DomainUserId;
                        filePath += @"\" + domainUserID + fileName.Replace(" ", "");

                        postedFile.SaveAs(filePath);
                        Document.ScanFileForVirus(filePath);

                        Document document = new Document(cachePolicy);
                        document.Id = 0;

                        FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read);
                        byte[] data = new byte[fs.Length];
                        fs.Read(data, 0, Convert.ToInt32(fs.Length));
                        fs.Close();

                        document.Blob = data;
                        document.DateCreated = DateTime.Now;
                        document.Name = fileName;
                        budgetAttachment.ElectronicFile = document;
                    }
                    else
                    {
                        errorReport += fileName + " is empty or invalid;" + "\r\n";
                    }
                }
                catch (Exception e)
                {
                    errorReport += e.ToString();
                }
            }
        }

        private void SetupPickers()
        {
            string pickerControl = "../ClinicalTrials/Controls/SponsorPicker.ascx";
            string pickerHostPage = "../Common/ControlHost.aspx";

            string features = string.Format("width={0},height={1},scrollbars=yes,resizable=yes,status=no",
                Settings.GetKeyValue("SearchPopupWindow.Width", 700),
                Settings.GetKeyValue("SearchPopupWindow.Height", 500));

            findSponsor.Attributes["onclick"] = string.Format("window.open('{0}?Load={1}', 'Picker', '{2}');return true;",
                pickerHostPage, pickerControl, features);
            findSponsor.Disabled = (budget.StatusCode == ClinicalTrialsConstants.BudgetStatusFinal);

            if (!Page.ClientScript.IsClientScriptBlockRegistered("SetSponsorSelection"))
            {
                string script = string.Format("<script language=\"javascript\">\n" +
                    "function SetSponsorSelection(id, name)\n" +
                    "{{\n" +
                    "\tvar o = document.getElementById('{0}');\n" +
                    "\tif (document.all)\n" +
                    "\to.innerText = name;\n" +
                    "\telse\n" +
                    "\to.textContent = name;\n" +
                    "\tvar o = document.getElementById('{1}');\n" +
                    "\to.value = id;\n" +
                    "}}\n" +
                    "</script>\n", sponsorName.ClientID, sponsorId.ClientID);

                Page.ClientScript.RegisterClientScriptBlock(GetType(), "SetSponsorSelection", script);
            }
            sponsorId.Attributes["style"] = "display:none;";

            pickerControl = "~/ClinicalTrials/Controls/PIPicker.ascx";
            findPI.Attributes["onclick"] = string.Format("window.open('{0}?Load={1}&Call=SetPISelection', 'Picker', '{2}');return true;",
                pickerHostPage, pickerControl, features);
            findPI.Disabled = (budget.StatusCode == ClinicalTrialsConstants.BudgetStatusFinal);

            if (!Page.ClientScript.IsClientScriptBlockRegistered("SetPISelection"))
            {
                string script = string.Format("<script language=\"javascript\">\n" +
                    "function SetPISelection(id, name)\n" +
                    "{{\n" +
                    "\tvar o = document.getElementById('{0}');\n" +
                    "\tif (document.all)\n" +
                    "\to.innerText = name;\n" +
                    "\telse\n" +
                    "\to.textContent = name;\n" +
                    "\tvar o = document.getElementById('{1}');\n" +
                    "\to.value = id;\n" +
                    "}}\n" +
                    "</script>\n", PIName.ClientID, PIId.ClientID);

                Page.ClientScript.RegisterClientScriptBlock(GetType(), "SetPISelection", script);
            }

            string personPickerControl = "~/ClinicalTrials/Controls/PersonPicker.ascx";
            string personPickerHostPage = "../Common/ControlHost.aspx";
            accessPI.Attributes["onclick"] = string.Format("window.open('{0}?Load={1}&Call=OnFirstClick', 'PersonPicker', '{2}');return true;",
                personPickerHostPage, personPickerControl, features);

            if (budget.StatusCode == ClinicalTrialsConstants.BudgetStatusFinal)
            {
                accessPI.Enabled = false;
            }

            if (!Page.ClientScript.IsClientScriptBlockRegistered("OnFirstClick"))
            {
                string script = string.Format("<script language=\"javascript\">\n" +
                    "function OnFirstClick(id)\n" +
                    "{{\n" +
                    "\tvar o = document.getElementById('{0}');\n" +
                    "\tif (o != null)\n" +
                    "{{\n" +
                    "\t\to.onClick = OnSecondClick();\n" +
                    "\t\to.click();\n" +
                    "}}\n" +
                    "}}\n" +
                    "</script>\n", accessPI.ClientID);

                Page.ClientScript.RegisterClientScriptBlock(GetType(), "OnFirstClick", script);
            }

            if (!Page.ClientScript.IsClientScriptBlockRegistered("secondClick"))
            {
                string script = string.Format("<script language=\"javascript\">\n" +
                    "function OnSecondClick()\n" +
                    "{{\n" +
                    "\treturn true;\n" +
                    "}}\n" +
                    "</script>\n");

                Page.ClientScript.RegisterClientScriptBlock(GetType(), "secondClick", script);
            }
        }

        private void InitializeControls()
        {
            breadCrumb.Add(
                "Work In Progress",
                "BudgetSetup.aspx", 2);

            PIId.Attributes["style"] = "display:none;";
            overheadRate.Attributes["onchange"] = "OnOverheadRateChanged( this );";
            otherNegotiatedRate.CssClass = "DataInputDisabled";
            otherNegotiatedRate.Enabled = false;
            negotiatedRateLabel.Attributes["class"] = "LabelDisabled";
            negotiatedRateRequiredValidator.Enabled = false;
            negotiatedRateValueValidator.Enabled = false;
        }

        private void OnTypeChanged(object sender, EventArgs arg)
        {
            if (studyType.SelectedValue == "ClinicalTrialBudgetStudyTypeGovernment" && institution.SelectedValue == "ClinicalTrialBudgetInstitutionBWH")
            {
                //default for government type of study is onsite 75%
                overheadRate.SelectedValue = "ClinicalTrialBudgetOverheadRateOnsiteBWH";
                DisableAllOtherControls();
            }
            if (studyType.SelectedValue == "ClinicalTrialBudgetStudyTypeGovernment" && institution.SelectedValue == "ClinicalTrialBudgetInstitutionMGH")
            {
                //default for government type of study is onsite 75%
                overheadRate.SelectedValue = "ClinicalTrialBudgetOverheadRateOnsiteMGH";
                DisableAllOtherControls();
            }
            if (studyType.SelectedValue == "ClinicalTrialBudgetStudyTypeIndustry")
            {
                overheadRate.SelectedValue = "ClinicalTrialBudgetOverheadRateCSCR";
                DisableAllOtherControls();
            }
            if (studyType.SelectedValue == "ClinicalTrialBudgetStudyTypeNonProfit")
            {
                overheadRate.SelectedValue = "ClinicalTrialBudgetOverheadRateNonProfitFoundation";
                DisableAllOtherControls();
            }
            if (studyType.SelectedValue == "ClinicalTrialBudgetStudyTypeFoundation")
            {
                overheadRate.SelectedValue = "ClinicalTrialBudgetOverheadRateNonProfitFoundation";

                DisableAllOtherControls();
            }
            if (studyType.SelectedValue == "ClinicalTrialBudgetStudyTypeOther")
            {
                overheadRate.SelectedValue = "ClinicalTrialBudgetOverheadRateOther";
                otherType.CssClass = "DataInput";
                otherType.Enabled = true;
                otherTypeLabel.Attributes["class"] = "Label";
                otherTypeValidator.Enabled = true;
                otherNegotiatedRate.Text = budget.OtherNegotiatedRate;
                otherNegotiatedRate.Enabled = true;
                otherNegotiatedRate.CssClass = "DataInput";
                negotiatedRateLabel.Attributes["class"] = "Label";
                negotiatedRateRequiredValidator.Enabled = true;
                negotiatedRateValueValidator.Enabled = true;
            }
        }

        private void LoadBudget()
        {
            budget = (Budget) cachePolicy.GetCachedObject(Budget.CacheKey);

            if (Session[Keys.IncomingDataKey] != null)
            {
                Hashtable h = (Hashtable) cachePolicy.GetCachedObject(Keys.IncomingDataKey);
                int budgetId = (int) h[Keys.BudgetIdKey];
                if (budgetId == 0)
                {
                    // New Budget
                    budget = new Budget(cachePolicy);
                    budget.StatusCode = ClinicalTrialsConstants.BudgetStatusNew;
                    budget.OriginatorPersonId = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId;
                    budget.Cache();
                }
                else if (budget == null || budget.Id != budgetId)
                {
                    budget = new Budget(cachePolicy);
                    budget.Load(DataAccess.GetConnectionString(), budgetId);
                    budget.Cache();
                }
                Session.Remove(Keys.IncomingDataKey);
            }
        }

        private void LoadControls()
        {
            userContext = (UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey);
            string Institution = userContext.Institution;
            ICachePolicy cachePolicyLoad = (ICachePolicy) Application[Names.ApplicationCachePolicyKey];
            RefCodes refCodes = (RefCodes) cachePolicyLoad.GetCachedObject(RefCodes.CacheKey);
            ArrayList overheadRates = refCodes.GetRefCodes("ClinicalTrialBudgetOverheadRate");
            overheadRate.DataTextField = "Meaning";
            overheadRate.DataValueField = "Code";
            overheadRate.DataSource = overheadRates;
            overheadRate.DataBind();
            overheadRate.Items.Insert(0, new ListItem("", ""));
            ArrayList primaryStudyLocations = refCodes.GetRefCodes("ClinicalTrialBudgetPrimaryStudyLocation");
            primaryStudyLocation.DataTextField = "Meaning";
            primaryStudyLocation.DataValueField = "Code";
            primaryStudyLocation.DataSource = primaryStudyLocations;
            primaryStudyLocation.DataBind();
            primaryStudyLocation.Items.Insert(0, new ListItem("", ""));
            ArrayList studyTypes = refCodes.GetRefCodes("ClinicalTrialBudgetStudyType");
            studyType.DataTextField = "Meaning";
            studyType.DataValueField = "Code";
            studyType.DataSource = studyTypes;
            studyType.DataBind();
            studyType.Items.Insert(0, new ListItem("", ""));
            institution.Items.Insert(0, new ListItem("BWH", "ClinicalTrialBudgetInstitutionBWH"));
            institution.Items.Insert(1, new ListItem("MGH", "ClinicalTrialBudgetInstitutionMGH"));
            //only disable the Institution drop down if user is not Administrator
            if (!CTAccessHelper.IsUserAdministrator(userContext.ModuleRoleBitmask))
            {
                institution.Enabled = false;
            }
            if (((Institution == "BWH") || (Institution == "MGH")) && (!CTAccessHelper.IsUserAdministrator(userContext.ModuleRoleBitmask)))
            {
                institution.Enabled = false;
            }
            else
            {
                institution.Enabled = true;
            }
        }

        private void BindControls()
        {
            if (budget.Id != 0)
            {
                studyShortTitle.Text = budget.StudyShortTitle;
                studyFullTitle.Text = budget.StudyFullTitle;
                sponsorProtocolNumber.Text = budget.SponsorProtocolNumber;
                sponsorId.Text = budget.SponsorId.ToString();


                // Sponsor name text
                Sponsor sponsor = new Sponsor(cachePolicy);
                sponsor.Load(DataAccess.GetConnectionString(), budget.SponsorId);
                sponsorName.Text = sponsor.Name;
                Session["SponsorChargeRate"] = sponsor.ChargeRate;

                studyType.SelectedValue = budget.StudyType;
                if (budget.StudyType == "ClinicalTrialBudgetStudyTypeOther")
                {
                    otherType.Enabled = true;
                    otherType.CssClass = "DataInput";
                    otherTypeLabel.Attributes["class"] = "Label";
                    otherTypeValidator.Enabled = true;
                }
                otherType.Text = budget.OtherType;
                PIInitiated.Checked = budget.PIInitiated;
                overheadRate.SelectedValue = budget.OverheadRateCode;
                if (budget.OverheadRateCode == "ClinicalTrialBudgetOverheadRateOther")
                {
                    otherNegotiatedRate.Text = budget.OtherNegotiatedRate;
                    otherNegotiatedRate.Enabled = true;
                    otherNegotiatedRate.CssClass = "DataInput";
                    negotiatedRateLabel.Attributes["class"] = "Label";
                    negotiatedRateRequiredValidator.Enabled = true;
                    negotiatedRateValueValidator.Enabled = true;
                }
                primaryStudyLocation.SelectedValue = budget.PrimaryStudyLocationCode;
                folderNumber.Text = budget.FolderNumber;
                numberOfVisits.Text = budget.SubjectVisits.ToString();
                numberOfSubjects.Text = budget.EnrolledSubjects.ToString();
                IRBProtocolNumber.Text = budget.IRBProtocolNumber;
                institution.SelectedValue = budget.InstitutionCode;
                accessLevel.Text = budget.AccessLevel.ToString();
                fwkDomainId.Text = budget.FwkDomainUserId.ToString();

                User originator = new User(cachePolicy);
                originator.Load(DataAccess.GetConnectionString(), budget.OriginatorPersonId);
                originatorUsername.Text = originator.Username;
                originatorName.Text = originator.FirstName + " " + originator.LastName;
                originatorOrganization.Text = originator.Organization;
                User pi = new User(cachePolicy);
                pi.Load(DataAccess.GetConnectionString(), budget.PIPersonId);
                PIName.Text = string.Format("{0} {1}", pi.FirstName, pi.LastName);
                PIId.Text = pi.DomainUserId.ToString();
                ArrayList attachments = BudgetAttachment.GetDocuments(budget.Id, cachePolicy);
                attachmentsGrid.DataSource = attachments;
                attachmentsGrid.DataBind();
            }
            else
            {
                userContext = (UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey);
                User originator = new User(cachePolicy);
                originator.Load(DataAccess.GetConnectionString(), userContext.PersonId);
                originatorUsername.Text = originator.Username;
                originatorName.Text = originator.FirstName + " " + originator.LastName;
                originatorOrganization.Text = originator.Organization;
                accessLevel.Text = userContext.RightBitmask.ToString();
                fwkDomainId.Text = userContext.DomainUserId.ToString();
                if (userContext.Institution == "BWH")
                {
                    institution.SelectedValue = "ClinicalTrialBudgetInstitutionBWH";
                }
                if (userContext.Institution == "MGH")
                {
                    institution.SelectedValue = "ClinicalTrialBudgetInstitutionMGH";
                }
            }
        }

        private void SetBudget()
        {
            if (((Budget) cachePolicy.GetCachedObject(Budget.CacheKey)).StatusCode == ClinicalTrialsConstants.BudgetStatusNew)
            {
                ((Budget) cachePolicy.GetCachedObject(Budget.CacheKey)).StatusCode = ClinicalTrialsConstants.BudgetStatusInProgress;
            }

            budget.AccessLevel = Int32.Parse(accessLevel.Text);
            budget.FwkDomainUserId = Int32.Parse(fwkDomainId.Text);
            budget.StudyShortTitle = studyShortTitle.Text;
            budget.StudyFullTitle = studyFullTitle.Text;
            budget.SponsorId = Int32.Parse(sponsorId.Text);
            budget.SponsorProtocolNumber = sponsorProtocolNumber.Text;
            budget.StudyType = studyType.SelectedValue;
            if (budget.StudyType == "ClinicalTrialBudgetStudyTypeOther")
            {
                otherType.Enabled = true;
                otherType.CssClass = "DataInput";
                otherTypeLabel.Attributes["class"] = "Label";
                otherTypeValidator.Enabled = true;
            }
            else
            {
                otherType.Enabled = false;
                otherType.CssClass = "DataInputDisabled";
                otherTypeLabel.Attributes["class"] = "LabelDisabled";
                otherTypeValidator.Enabled = false;
            }
            budget.OtherType = otherType.Text;
            budget.PIPersonId = Int32.Parse(PIId.Text);
            budget.PIInitiated = PIInitiated.Checked;
            budget.OverheadRateCode = overheadRate.SelectedValue;
            if (budget.OverheadRateCode == "ClinicalTrialBudgetOverheadRateOther")
            {
                otherNegotiatedRate.Enabled = true;
                otherNegotiatedRate.CssClass = "DataInput";
                negotiatedRateLabel.Attributes["class"] = "Label";
                negotiatedRateRequiredValidator.Enabled = true;
                negotiatedRateValueValidator.Enabled = true;
                budget.OtherNegotiatedRate = otherNegotiatedRate.Text;
            }
            else
            {
                otherNegotiatedRate.Enabled = false;
                otherNegotiatedRate.CssClass = "DataInputDisabled";
                negotiatedRateLabel.Attributes["class"] = "LabelDisabled";
                negotiatedRateRequiredValidator.Enabled = false;
                negotiatedRateValueValidator.Enabled = false;
            }
            budget.PrimaryStudyLocationCode = primaryStudyLocation.SelectedValue;
            budget.FolderNumber = folderNumber.Text;
            budget.SubjectVisits = Int32.Parse(numberOfVisits.Text);
            budget.EnrolledSubjects = Int32.Parse(numberOfSubjects.Text);
            budget.IRBProtocolNumber = IRBProtocolNumber.Text;
            budget.InstitutionCode = institution.SelectedValue;
            if (budget.Id != 0 && budget.InstitutionCode != institution.SelectedValue)
            {
                BudgetProcedures budgetProcedures = budget.BudgetProcedures;
                for (int i = budgetProcedures.Count - 1; i >= 0; --i)
                {
                    BudgetProcedure budgetProcedure = budgetProcedures[i];
                    budgetProcedures.RemoveBudgetProcedure(budgetProcedure);
                }
                budgetProcedures.Save(DataAccess.GetConnectionString());
            }
        }

        private void DisableControls(Control formControl)
        {
            switch (formControl.GetType().ToString())
            {
                case "System.Web.UI.WebControls.TextBox":
                    (formControl as TextBox).Enabled = false;
                    break;
                case "System.Web.UI.WebControls.DropDownList":
                    (formControl as DropDownList).Enabled = false;
                    break;
                case "System.Web.UI.WebControls.CheckBox":
                    (formControl as CheckBox).Enabled = false;
                    break;
                case "System.Web.UI.WebControls.CheckBoxList":
                    (formControl as CheckBoxList).Enabled = false;
                    break;
                case "System.Web.UI.WebControls.RadioButton":
                    (formControl as RadioButton).Enabled = false;
                    break;
                case "System.Web.UI.WebControls.RadioButtonList":
                    (formControl as RadioButtonList).Enabled = false;
                    break;
                case "System.Web.UI.WebControls.Button":
                    if ((formControl.ID == "setup") || (formControl.ID == "staffing")
                        || (formControl.ID == "visits") || (formControl.ID == "otherCosts") || (formControl.ID == "summary"))
                    {
                        (formControl as Button).Enabled = true;
                    }
                    else
                    {
                        (formControl as Button).Enabled = false;
                    }
                    break;
                default:
                    foreach (Control childControl in formControl.Controls)
                    {
                        DisableControls(childControl);
                    }
                    break;
            }
        }

        #endregion

        #region Overrides

        /// <summary>
        /// Used to disable controls based on budget status
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            SetupPickers();

            HtmlForm budgetSetupForm = (HtmlForm) Page.FindControl("BudgetSetupForm");
            budget = (Budget) cachePolicy.GetCachedObject(Budget.CacheKey);
            userContext = (UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey);
            int accessLevel;

            if (budget.StatusCode == ClinicalTrialsConstants.BudgetStatusNew)
            {
                accessLevel = userContext.RightBitmask;
                regUsersMessage.Text = "Please Save Budget Before Adding Users.";
                accessPI.Enabled = false;
            }
            else
            {
                accessLevel = budget.AccessLevel;
                regUsersMessage.Text = "* You can add only registered Insight Users.";
                accessPI.Enabled = true;
            }

            //if budget status is final, check if user has rights to modify final (amend) if not disable controls
            if (budget.StatusCode == ClinicalTrialsConstants.BudgetStatusFinal)
            {
                accessPI.Enabled = findPI.Disabled = findSponsor.Disabled = newFile.Disabled = true;
                foreach (Control formControl in budgetSetupForm.Controls)
                {
                    DisableControls(formControl);
                }
            }

            if (!CTAccessHelper.IsUserAdministrator(accessLevel))
            {
                //if budget status is pending, check if user has rights to modify pending if not disable controls
                if ((budget.StatusCode == ClinicalTrialsConstants.BudgetStatusInProgress)
                    || (budget.StatusCode == ClinicalTrialsConstants.BudgetStatusAmended))
                {
                    if (!CTAccessHelper.IsUserModifyPending(accessLevel))
                    {
                        findPI.Disabled = findSponsor.Disabled = newFile.Disabled = true;
                        foreach (Control formControl in budgetSetupForm.Controls)
                        {
                            DisableControls(formControl);
                        }
                    }
                }
            }
        }

        #endregion

        #region Web Form Designer generated code

        ///<summary>Initializes components used by the page.</summary>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.attachmentsGrid.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.OnItemCommand);
            this.ctAccess.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemBound);
            this.Load += new System.EventHandler(this.OnPageLoad);
            studyType.SelectedIndexChanged += new EventHandler(OnTypeChanged);
        }

        #endregion

        private void OnItemBound(object sender, DataGridItemEventArgs e)
        {
            DataRowView view = (DataRowView) e.Item.DataItem;
            if (UserDTAccess.Rows.Count != 0)
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    ((CheckBox) (e.Item.Cells[2]).Controls[1]).Checked = Convert.ToBoolean(view["IsReadPending"]);
                    ((CheckBox) (e.Item.Cells[3]).Controls[1]).Checked = Convert.ToBoolean(view["IsReadFinal"]);
                    ((CheckBox) (e.Item.Cells[4]).Controls[1]).Checked = Convert.ToBoolean(view["IsModifyPending"]);
                }
            }
        }

        /// <summary>
        /// Saving People that have access to the budget
        /// </summary>
        protected void OnDataGridSave(object sender, EventArgs e)
        {
            budget = (Budget) cachePolicy.GetCachedObject(Budget.CacheKey);

            if (UserDTAccess.Rows.Count != 0)
            {
                foreach (DataGridItem item in ctAccess.Items)
                {
                    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                    {
                        int readPending = 0;
                        int readFinal = 0;
                        int modifyPending = 0;

                        int userDomainId = Convert.ToInt32(item.Cells[5].Text);
                        if (((CheckBox) item.Cells[2].Controls[1]).Checked)
                        {
                            readPending = 1;
                        }
                        if (((CheckBox) item.Cells[3].Controls[1]).Checked)
                        {
                            readFinal = 1;
                        }
                        if (((CheckBox) item.Cells[4].Controls[1]).Checked)
                        {
                            modifyPending = 1;
                        }

                        if ((modifyPending == 1) && (readPending == 0))
                        {
                            ((CheckBox) item.Cells[2].Controls[1]).Checked = true;
                        }

                        DataAccess.ExecuteNonQuery(
                            DataAccess.GetConnectionString(),
                            "UpdateUserAccessToClinicalTrialBudget",
                            DataAccess.BuildSqlParameterArray("@domainUserId", SqlDbType.Int, userDomainId,
                                "@budgetId", SqlDbType.Int, budget.Id,
                                "@readPending", SqlDbType.Int, readPending,
                                "@readFinal", SqlDbType.Int, readFinal,
                                "@modifyPending", SqlDbType.Int, modifyPending));
                    }
                }
                ReloadUserAccessTable();
                Session["newPIaccess"] = "";
                Session["PIName"] = "";
            }
            else
            {
                AddBlankRow();
            }
        }

        private void AddBlankRow()
        {
            if ((Session["newPIaccess"] != null) && ((string) Session["newPIaccess"] != ""))
            {
                int readPending = 1;
                int readFinal = 1;
                int modifyPending = 1;

                DataAccess.ExecuteNonQuery(
                    DataAccess.GetConnectionString(),
                    "UpdateUserAccessToClinicalTrialBudget",
                    DataAccess.BuildSqlParameterArray("@domainUserId", SqlDbType.Int, Session["newPIaccess"],
                        "@budgetId", SqlDbType.Int, budget.Id,
                        "@readPending", SqlDbType.Int, readPending,
                        "@readFinal", SqlDbType.Int, readFinal,
                        "@modifyPending", SqlDbType.Int, modifyPending));
            }
            //set to null to refresh the dataset
            ReloadUserAccessTable();
            Session["newPIaccess"] = "";
            Session["PIName"] = "";
        }

        private void ReloadUserAccessTable()
        {
            userDTAccess = null;
            ctAccess.DataSource = UserDTAccess;
            ctAccess.DataBind();
        }

        protected void OnAddUser(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            DataRow r;
            DataColumn column;
            //saves only if user stored in the session
            if ((Session["newPIaccess"] != null) && ((string) Session["newPIaccess"] != ""))
            {
                //only if no users in the table prior
                if (UserDTAccess.Rows.Count == 0)
                {
                    column = new DataColumn();
                    column.DataType = Type.GetType("System.String");
                    column.ColumnName = "PIName";
                    dt.Columns.Add(column);

                    column = new DataColumn();
                    column.DataType = Type.GetType("System.String");
                    column.ColumnName = "UserName";
                    dt.Columns.Add(column);

                    column = new DataColumn();
                    column.DataType = Type.GetType("System.String");
                    column.ColumnName = "UserDomainId";
                    dt.Columns.Add(column);

                    column = new DataColumn();
                    column.DataType = Type.GetType("System.Object");
                    column.ColumnName = "IsReadPending";
                    dt.Columns.Add(column);

                    column = new DataColumn();
                    column.DataType = Type.GetType("System.Object");
                    column.ColumnName = "IsReadFinal";
                    dt.Columns.Add(column);

                    column = new DataColumn();
                    column.DataType = Type.GetType("System.Object");
                    column.ColumnName = "IsModifyPending";
                    dt.Columns.Add(column);
                    rpending.ID = "IsReadPending";
                    rfinal.ID = "IsReadFinal";
                    mpending.ID = "IsModifyPending";

                    DataRow row = dt.NewRow();
                    row["PIName"] = Session["PIName"];
                    row["Username"] = "";
                    row["IsReadPending"] = rpending;
                    row["IsReadFinal"] = rfinal;
                    row["IsModifyPending"] = mpending;
                    row["UserDomainId"] = Session["newPIaccess"];
                    dt.Rows.Add(row);
                    ctAccess.DataSource = dt;
                    ctAccess.DataBind();
                }
                else
                {
                    //only when adding more users to existing records
                    dt = UserDTAccess;
                    r = dt.NewRow();
                    r["PIName"] = Session["PIName"];
                    r["Username"] = "";
                    r["IsReadPending"] = "0";
                    r["IsReadFinal"] = "0";
                    r["IsModifyPending"] = "0";
                    r["UserDomainId"] = Session["newPIaccess"];
                    dt.Rows.Add(r);
                    ctAccess.DataSource = dt;
                    ctAccess.DataBind();
                }
            }
        }
    }
}